package com.haoshuang.zhouzhoubang.ui.activity

import android.Manifest
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Canvas
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.provider.Settings
import android.util.Log
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.widget.NestedScrollView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.LinearSnapHelper
import androidx.recyclerview.widget.PagerSnapHelper
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.haoshuang.zhouzhoubang.R
import com.haoshuang.zhouzhoubang.databinding.ActivityServiceLog4Binding
import com.haoshuang.zhouzhoubang.model.bean.Image42Bean
import com.haoshuang.zhouzhoubang.model.bean.ImageBean9
import com.haoshuang.zhouzhoubang.ui.adapter.ImageAdapter25
import com.haoshuang.zhouzhoubang.ui.adapter.YdAdapter
import com.haoshuang.zhouzhoubang.ui.dialog.CustomBottomSharePopup
import com.haoshuang.zhouzhoubang.ui.dialog.Tis2Dialog
import com.haoshuang.zhouzhoubang.ui.vm.ServiceLog4ViewModel
import com.haoshuang.zhouzhoubang.utils.PaymentUtil
import com.haoshuang.zhouzhoubang.utils.PermissionHelper
import com.lxj.xpopup.XPopup
import com.mufeng.libs.base.BaseVMActivity
import com.mufeng.libs.core.setOnItemClick
import com.mufeng.libs.state.observeState
import com.mufeng.libs.utils.startPage
import com.mufeng.libs.utils.toast
import com.mufeng.libs.utils.view.clickWithTrigger
import com.mufeng.libs.utils.view.load
import java.io.FileNotFoundException
import java.io.IOException
import java.io.OutputStream
import java.util.ArrayList


/**
 *  
 */
class ServiceLog4Activity : BaseVMActivity<ServiceLog4ViewModel, ActivityServiceLog4Binding>() {

    override fun initView(savedInstanceState: Bundle?) {
        binding.appBar.ivBack.clickWithTrigger { finish() }
        binding.appBar.tvTitle.text = "分享"
    }
    var list= arrayListOf<Image42Bean>()
    var list2= arrayListOf<ImageBean9>()
    var adapter: ImageAdapter25?=null
    var adapter2: YdAdapter?=null
    var gson= Gson()
    var ids="0"
    fun getBitmap(view: ConstraintLayout): Bitmap? {
        view.isDrawingCacheEnabled = true
        view.buildDrawingCache() //启用DrawingCache并创建位图
        val bitmap = Bitmap.createBitmap(view.drawingCache) //创建一个DrawingCache的拷贝，因为DrawingCache得到的位图在禁用后会被回收
        view.isDrawingCacheEnabled = false //禁用DrawingCahce否则会影响性能
        return bitmap

        /*   var h = 0
           var bitmap: Bitmap? = null
           for (i in 0 until scrollView.getChildCount()) {
               h += scrollView.getChildAt(i).getHeight()
               scrollView.getChildAt(i).setBackgroundColor(Color.parseColor("#ffffff"))
           }
           bitmap = Bitmap.createBitmap(scrollView.getWidth(), h, Bitmap.Config.RGB_565)
           val canvas = Canvas(bitmap)
           scrollView.draw(canvas)*/

      /*  var h = 0

        // 获取listView实际高度
        for (i in 0 until view.getChildCount()) {
            h += view.getChildAt(i).getHeight()
            view.getChildAt(i).setBackgroundResource(R.color.white)
        }

        // 创建对应大小的bitmap
        var bitmap = Bitmap.createBitmap(view.getWidth(), h,
            Bitmap.Config.RGB_565)
        val canvas = Canvas(bitmap)
        view.draw(canvas)*/
        /*  val width = view.width
          val height = view.height
          val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565)
          val canvas = Canvas(bitmap)
          view.draw(canvas)*/
        return bitmap
    }
    fun addBitmapToAlbum(
        context: Context,
        bitmap: Bitmap
    ) {
        val displayName = "111jpg"
        val mimeType = "image/jpeg"
        val compressFormat = Bitmap.CompressFormat.JPEG

        val values = ContentValues()
        values.put(MediaStore.MediaColumns.DISPLAY_NAME, displayName)
        values.put(MediaStore.MediaColumns.MIME_TYPE, mimeType)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DCIM)
        } /*else {
            values.put(
                MediaStore.MediaColumns.DATA,
                Environment.getExternalStorageDirectory().path + Environment.DIRECTORY_DCIM + displayName
            )
        }*/
        val contentResolver = context.contentResolver
        val uri: Uri? = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
        //ToastUtils.show("保存成功 ")
        if (uri != null) {
            var outputStream: OutputStream? = null
            try {
                outputStream = contentResolver.openOutputStream(uri)
                bitmap.compress(compressFormat, 100, outputStream)
                outputStream?.close()
                try {
                    when (type9) {

                        2 -> {
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                                var phth = getFileUri(context, uri)
                                PaymentUtil.wxShareALl2(context, bitmap, false, phth)
                            } else {
                                PaymentUtil.wxShareALl2(
                                    context,
                                    bitmap,
                                    false,
                                    uri.path
                                )
                            }

                        }
                        3 -> {
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                                var phth = getFileUri(context, uri)
                                PaymentUtil.wxShareALl2(context, bitmap, true, phth)
                            } else {
                                PaymentUtil.wxShareALl2(
                                    context,
                                    bitmap,
                                    true,
                                    uri.path
                                )
                            }


                        }
                    }

                } catch (e: Exception) {

                }
            } catch (e: FileNotFoundException) {
                e.printStackTrace()
            } catch (e: IOException) {
                e.printStackTrace()
            }
            if (outputStream != null) {
            }
        }
    }
    fun getFileUri(context: Context, contentUri: Uri): String? {
        // 授权给微信访问路径
        context.grantUriPermission(
            "com.tencent.mm",  // 这里填微信包名
            contentUri, Intent.FLAG_GRANT_READ_URI_PERMISSION
        )
        return contentUri.toString() // contentUri.toString() 即是以"content://"开头的用于共享的路径
    }
    var type9 = 2
    override fun initData() {
    var    bean=intent.getStringExtra("bean")
        ids= intent.getStringExtra("ids").toString()
        vm.getData2("id" to ids)
        list=gson.fromJson(bean, object : TypeToken<ArrayList<Image42Bean>>() {}.getType())
        for (b in list){
            list2.add(ImageBean9(0))
        }
        list2[0].isCheck=1
        adapter= ImageAdapter25(list)
        adapter2= YdAdapter(list2)
        binding.apply {
            tvShare.clickWithTrigger {
                val popupView = CustomBottomSharePopup(this@ServiceLog4Activity){
                    when(it){
                        R.id.ivBottomPopWX -> {
                            type9=2
                            PermissionHelper.requestPermission(
                                mActivity,
                                "存储权限使用说明",
                                "用于快速保存分享图片",
                                Manifest.permission.READ_EXTERNAL_STORAGE,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE
                            ) {
                                if (it) {
                                    var bmp = getBitmap(clShare)
                                    addBitmapToAlbum(mActivity, bmp!!)
                                } else {
                                    XPopup.Builder(mActivity)
                                        .asCustom(Tis2Dialog(mActivity, "开启读写权限是为了保存图片") {
                                            val intent = Intent()
                                            intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
                                            intent.data = Uri.parse("package:" + getPackageName())
                                            startActivity(intent)

                                        })
                                        .show()
                                }
                            }
                        }
                        R.id.ivBottomPopWXMoments -> {
                            type9=3
                            PermissionHelper.requestPermission(
                                mActivity,
                                "存储权限使用说明",
                                "用于快速保存分享图片",
                                Manifest.permission.READ_EXTERNAL_STORAGE,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE
                            ) {
                                if (it) {
                                    var bmp = getBitmap(clShare)
                                    addBitmapToAlbum(mActivity, bmp!!)
                                } else {
                                    XPopup.Builder(mActivity)
                                        .asCustom(Tis2Dialog(mActivity, "开启读写权限是为了保存图片") {
                                            val intent = Intent()
                                            intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
                                            intent.data = Uri.parse("package:" + getPackageName())
                                            startActivity(intent)

                                        })
                                        .show()
                                }
                            }
                        }
                    }
                }
                XPopup.Builder(this@ServiceLog4Activity)
                    .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                    .asCustom(popupView)
                    .show()
            }
            var lay=LinearLayoutManager(this@ServiceLog4Activity)
            var lay2=LinearLayoutManager(this@ServiceLog4Activity)
            lay.orientation=LinearLayoutManager.HORIZONTAL
            lay2.orientation=LinearLayoutManager.HORIZONTAL
            rvList.layoutManager=lay
            rvList2.layoutManager=lay2
            rvList.adapter=adapter
            rvList2.adapter=adapter2
            var helper=PagerSnapHelper()
            helper.attachToRecyclerView(rvList)
            rvList.addOnScrollListener(object: RecyclerView.OnScrollListener() {
                override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                    super.onScrollStateChanged(recyclerView, newState)
                    if(newState == RecyclerView.SCROLL_STATE_IDLE){
                        try {
                            val currentPosition = (recyclerView.getChildAt(0).layoutParams as RecyclerView.LayoutParams).viewAdapterPosition
                            for (b in list2){
                                b.isCheck=0
                            }
                            list2[currentPosition].isCheck=1
                            adapter2?.notifyDataSetChanged()
                        } catch (e:Exception ) {
                        }
                    }
                }
            })
            adapter?.setOnItemClick { view, position,_ ->
                var list21= arrayListOf<String>()
                var url2=""
                for (b in list){
                    if (b.isVideo==1){
                        url2=b.image
                    }else{
                        list21.add(b.image)
                    }
                }
                if (list[position].isVideo==0){
                    startPage<LookActivity>("imgBeen" to list21,"position" to position)
                }else{
                    startPage<VideoActivity>("url" to url2)
                }
            }
        }
    }

    override fun startObserve() {
        vm.getData2.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                if (code!="402"){
                    toast(msg)
                }
            }
            onSuccess {
                dismissLoading()
                if (it!=null){
                    Glide.with(this@ServiceLog4Activity)
                        .load(it.qrcode_url)
                        .skipMemoryCache(true) // 不使用内存缓存
                        .diskCacheStrategy(DiskCacheStrategy.NONE)
                        .into(binding.ivImage4)
                    binding.ivImage6.load(it.content_url)
                    Log.e("diskCacheStrategy",it.qrcode_url)

                   // binding.ivImage4.load(it.qrcode_url)

                    binding.ivText.text="我是周周家服${it.master_name}师傅，\n" +
                            "我为自己代言 ${it.service_time}，为${it.user_name}客户提供服务"
                }
            }
        }
    }

}